package com.bedrock.project.inside.service.impl;

import java.sql.SQLException;
import java.util.*;

import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bedrock.common.utils.DateUtils;
import com.bedrock.common.utils.IdWord;
import com.bedrock.project.enums.FlowStatic;
import com.bedrock.project.enums.JobberStatic;
import com.bedrock.project.inside.entity.Interviewer;
import com.bedrock.project.inside.entity.InterviewerFlow;
import com.bedrock.project.inside.entity.RecruitEntity;
import com.bedrock.project.inside.entity.WaitAffair;
import com.bedrock.project.inside.mapper.InterviewerMapper;
import com.bedrock.project.inside.mapper.RecruitMapper;
import com.bedrock.project.inside.service.IRecruitService;
import com.bedrock.project.inside.service.IWaitAffairService;
import com.bedrock.project.inside.vo.request.InterviewerFlowVo;
import com.bedrock.project.inside.vo.response.InterviewEmailVo;


/**
 * 招聘Service业务层处理
 * 
 * @author bedrock
 * @date 2020-04-07
 */
@Service
public class RecruitServiceImpl implements IRecruitService
{

    private static final Logger log = LoggerFactory.getLogger(RecruitServiceImpl.class);

    @Autowired
    private InterviewerMapper interviewerMapper;

    @Autowired
    private RecruitMapper recruitMapper;

    @Autowired
    private IWaitAffairService waitAffairService;

    /**
     * 查询招聘
     * 
     * @param id 招聘ID
     * @return 招聘
     */
    @Override
    public RecruitEntity selectRecruitEntityById(Long id)
    {
        return recruitMapper.selectRecruitEntityById(id);
    }

    /**
     * 查询招聘列表
     * 
     * @param recruitEntity 招聘
     * @return 招聘
     */
    @Override
    public List<RecruitEntity> selectRecruitEntityList(RecruitEntity recruitEntity)
    {



        return recruitMapper.selectRecruitEntityList(recruitEntity);
    }

    /**
     * 新增招聘
     * 
     * @param recruitEntity 招聘
     * @return 结果
     */
    @Override
    public int insertRecruitEntity(RecruitEntity recruitEntity)
    {
        recruitEntity.setCreateTime(DateUtils.getNowDate());
        return recruitMapper.insertRecruitEntity(recruitEntity);
    }

    /**
     * 修改招聘
     * 
     * @param recruitEntity 招聘
     * @return 结果
     */
    @Override
    public int updateRecruitEntity(RecruitEntity recruitEntity)
    {
        recruitEntity.setUpdateTime(DateUtils.getNowDate());
        return recruitMapper.updateRecruitEntity(recruitEntity);
    }

    /**
     * 批量删除招聘
     * 
     * @param ids 需要删除的招聘ID
     * @return 结果
     */
    @Override
    public int deleteRecruitEntityByIds(Long[] ids)
    {
        return recruitMapper.deleteRecruitEntityByIds(ids);
    }

    /**
     * 删除招聘信息
     * 
     * @param id 招聘ID
     * @return 结果
     */
    @Override
    public int deleteRecruitEntityById(Long id)
    {
        return recruitMapper.deleteRecruitEntityById(id);
    }

    /**
     *  求职者分配面试
     * @param interviewer
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public synchronized String viewerset(Interviewer interviewer) throws Exception{

        String result="";
        List<Interviewer>  viewerList = interviewerMapper.selectInterviewerList(interviewer);
        if(viewerList == null || viewerList.size()==0){
            // 没有可分配的面试官
            result="分配失败，没有可预约的面试官";
        }else{

            try{

                // 做三件事1 修改面试官状态  2 插入流程表  3 修改求职表 4 插入事项表
                // 分配 , 修改面试官池表，状态改为非空闲状态
                Random random = new Random();
                int n = random.nextInt(viewerList.size());
                Interviewer viewer =   viewerList.get(n);
                // 非空闲
                viewer.setViewStatic(2);
                //viewer.setDoUserId(interviewer.getDoUserId());
                // 修改面试官数据状态，
                interviewerMapper.updateStViewatic(viewer);


                // 修改求职者表 将状态改为进行中, 同时加入面试官ID
                RecruitEntity recruitEntity = new RecruitEntity();
                // 面试官池中的user_id 表示为面试官Id
                recruitEntity.setDoUserId(viewer.getUserId());
                recruitEntity.setId(interviewer.getRecuritId());
                recruitMapper.updateDoUserId(recruitEntity);

                // 分配完之后插入流表程表
                InterviewerFlow flow = new InterviewerFlow();
                Long flowId = IdWord.getId();
                flow.setId(flowId);
                // 面试官表 ID
                flow.setViewerId(viewer.getId());
                // 求职者Id
                flow.setRecruitId(interviewer.getRecuritId());
                // 待筛选
                flow.setFlowStatic(1);
                flow.setCreateBy(Long.parseLong(interviewer.getCreateBy()));
                flow.setCreateTime(new Date());
                // 插入数流程表
                recruitMapper.insertRecruitFlow(flow);



                // 分配完之后插入事项表
                WaitAffair affair = new WaitAffair();
                affair.setId(IdWord.getId());
                affair.setViewFlowId(flowId);
                // 主题
                affair.setAffairTitle(interviewer.getJoberName());
                // 处理人 面试官
                affair.setDoUserId(viewer.getUserId());
                // 待办事件类型
                affair.setAffairType(1);

                // 创建人 及时间  HR
                affair.setCreateBy(interviewer.getCreateBy());
                affair.setCreateTime(new Date());
                affair.setUpdateTime(new Date());
                // 插入数据库
                waitAffairService.insertWaitAffair(affair);

                result="分配成功";
            }catch (Exception ex){
                result="分配失败，未知错误，请联系管理员";
            }

        }

        return result;
    }

    /**
     * 面试流程流转
     * @param flowVo
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public String flowTo(InterviewerFlowVo flowVo) throws Exception{

        // 求职者状态 状态 :  1 待筛选
        // 2 筛选未通过
        // 3 待预约
        // 4 面试   ： HR 预约之后就表示面试开始
        // 5 面试未通过
        // 6 面试通过待定 7 结束

        // 正常流程规则：如果上个状态是1 ， 当前传入状态必须是2 或 者 3
        // 如果是3 ，当前传入状态必须是 4
        // 如果是 4 ，当关传入状态必须是 5 和 6
        // 如果是 6 ，当关传入状态必须是7

        // 如果上个状态是2 或者 是5 的话，不做修改，表示流程非正常结束

        // 首先查询流程的上一状态
        InterviewerFlow flow = recruitMapper.findFlowById(flowVo.getFlowId());
        // 是否可以正常变更流程状态
        boolean isFlag = false;
        // 判断上一状态，其中2，5，不用处理
        switch (flow.getFlowStatic()) {
            case 1:
                // 必须要传筛选评语 , 以及2 或 3的状态
                if(flowVo.getChooseRemark()!=null ||
                        FlowStatic.CHOOSE_PASS.getCode().equals(flowVo.getFlowStatic().toString()) ||
                        FlowStatic.WAIT_MAKE.getCode().equals(flowVo.getFlowStatic().toString())){

                    // 修改筛选评语
                    recruitMapper.updateRectuitStatic(null,flow.getRecruitId(),null,null,null,flowVo.getChooseRemark());

                    // 修改待办事项的流程处理人do_user_id
                    // 流程处理人简单 ：只会在HR 和 面试官中间流来转去,
                    // 现在是流给推荐人
                    waitAffairService.updateWaitFlowDouserId(flow.getRecUserId(),flow.getId());
                    isFlag = true;
                }
                break;
            case 3:
                if(FlowStatic.INTERVIEWER.getCode().equals(flowVo.getFlowStatic().toString())){
                    // 流转给面试官
                    waitAffairService.updateWaitFlowDouserId(flow.getViewUserId(),flow.getId());
                    isFlag = true;
                }

                break;
            case 4:
                // 必须要面试评语
                if(flowVo.getJobRemark()!=null
                        || flowVo.getFlowStatic().toString().equals(FlowStatic.INTERVIEWER_FAIL.getCode())
                        || flowVo.getFlowStatic().toString().equals(FlowStatic.INTERVIEWER_ACCEPTED.getCode())){
                    // 修改面试评语
                    recruitMapper.updateRectuitStatic(null,flow.getRecruitId(),null,null,flowVo.getJobRemark(),null);
                    // 流转给HR
                    waitAffairService.updateWaitFlowDouserId(flow.getRecUserId(),flow.getId());
                    isFlag = true;
                }
                break;
            case 6:
                if(flowVo.getFlowStatic().toString().equals(FlowStatic.FINISH.getCode())){
                    // 修改处理人为空
                    waitAffairService.updateWaitFlowDouserId(null,flow.getId());
                    isFlag=true;
                }
                break;
            default:
                isFlag=false;
        }

        String result = "";
       // 判断当前的操作是否符正常的流程，正常的就修改流程表
        if(isFlag){
            // 将数据的流程状态改为新的状态
            //flow.setFlowStatic(flowVo.getFlowStatic());
            if(updateFlow(flow,flowVo)){
                result = "流程修改成功";
            }else{
                result = "流程修失败";
            }

        }else{
            result = "流程状态为:"+flow.getFlowStatic()+" 与当前流程状态："+flowVo.getFlowStatic()+"及参数不匹配";
        }

        return result;

    }

    /**
     *
     * @param flow
     */
    @Transactional(rollbackFor=Exception.class)
    public boolean updateFlow(InterviewerFlow flow,InterviewerFlowVo vo){
        try{

            // 判断状态是否为2 5 7 ，如果是，则修改求职者的表，将jober_static状态改为已结束
            if(FlowStatic.CHOOSE_PASS.getCode().equals(vo.getFlowStatic().toString())
                    || FlowStatic.INTERVIEWER_FAIL.getCode().equals(vo.getFlowStatic().toString())
                    || FlowStatic.FINISH.getCode().equals(vo.getFlowStatic().toString())
            ){
                // 改为已结束
                recruitMapper.updateRectuitStatic(Integer.parseInt(JobberStatic.DONE.getCode()),flow.getRecruitId(),null,null,null,null);

                // 修改面试官池表，将当前的面试官状态改为1 空闲中
                Interviewer view = new Interviewer();
                view.setId(flow.getViewerId());
                view.setViewStatic(1);
                interviewerMapper.updateStViewatic(view);

                // 并且如果状态为 7 时，isEntry有值时，也需要修改
                if(FlowStatic.FINISH.getCode().equals(vo.getFlowStatic().toString())){
                    recruitMapper.updateRectuitStatic(null,flow.getRecruitId(),vo.getIsEntry(),null,null,null);
                }
            }

            // 如果状态为3 时，还需要改预约时间
            if(FlowStatic.WAIT_MAKE.getCode().equals(flow.getFlowStatic().toString())){
                String makeTime = new  java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(vo.getMakeTime());
                recruitMapper.updateRectuitStatic(null,flow.getRecruitId(),null,makeTime,null,null);
            }

            flow.setFlowStatic(vo.getFlowStatic());
            // 修改流程表
            recruitMapper.updateFlowById(flow);
        }catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }

        return true;

    }

    @Override
    public void updateVitaeUrl(String url,Long recruitId,Long createBy){
        try{

            Map map = new HashMap<>(10);
            map.put("recruitId",recruitId);
            map.put("createBy",createBy);
            map.put("vitaeUrl",url);
            map.put("id",recruitId);
            recruitMapper.updateVitaeUrl(map);
        }catch (SQLException ex){
            ex.printStackTrace();
            log.error("简历上传错误：{}",ex);
        }

    }

    @Override
    public List<InterviewEmailVo> sumWeeklyInterView() {
        List<InterviewEmailVo> list = recruitMapper.sumWeeklyInterView();
        return list;
    }


}
